package com.abu.crms.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.abu.crms.config.exception.CRException;
import com.abu.crms.pojo.Classroom;
import com.abu.crms.pojo.Course;
import com.abu.crms.mapper.CourseMapper;
import com.abu.crms.service.ClassroomService;
import com.abu.crms.service.CourseService;
import com.abu.crms.utils.PageUtils;
import com.abu.crms.vo.CourseVo;
import com.abu.crms.vo.QueryConditionVO;
import com.abu.crms.vo.QueryCourseVo;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程表 服务实现类
 * </p>
 *
 * @author 阿布
 * @since 2021-02-03
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {

    @Autowired
    private ClassroomService classroomService;
    @Autowired
    private CourseMapper courseMapper;

    @Override
    public HashMap<String, Object> queryPageByCondition(QueryCourseVo queryCourseVo) {
        //        获取参数
        Long page = queryCourseVo.getPage();
        Long limit = queryCourseVo.getLimit();
        LocalDateTime startTime = queryCourseVo.getStartTime();
        LocalDateTime endTime = queryCourseVo.getEndTime();
        String searchParam = queryCourseVo.getSearchParam();
//        分页条件
        if (page == null) {
            page = 1L;
        }
        if (limit == null) {
            limit = 10L;
        }
        Page<Course> classroomPage = new Page<>(page, limit);
//        查询条件
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .like(StrUtil.isNotBlank(searchParam), "course_name", searchParam)
                .or()
                .like(StrUtil.isNotBlank(searchParam), "teacher_name", searchParam)
                .ge(startTime != null, "begin_time", startTime)
                .le(endTime != null, "end_time", endTime);
//        执行查询
        Page<Course> pageCourse = this.page(classroomPage, queryWrapper);
        List<Course> records = pageCourse.getRecords();

        List<CourseVo> courseVoList = records.stream().map(course -> {
            CourseVo courseVo = new CourseVo();
            BeanUtils.copyProperties(course, courseVo);
            //        获取课程的教室名字
            Classroom classroom = this.classroomService.getOne(new QueryWrapper<Classroom>().eq("classroom_id", course.getClassroomId()).select("classroom_name"));
            if (classroom != null) {
                String classroomName = classroom.getClassroomName();
                courseVo.setClassroomName(classroomName);
            }
            //        获取时长
            LocalDateTime begin = course.getBeginTime();
            LocalDateTime end = course.getEndTime();
//            获取时差
            Duration duration = Duration.between(begin, end);
            long seconds = duration.getSeconds();
            Float durationSeconds = Convert.toFloat(seconds);
            courseVo.setDuration(durationSeconds / 60);
            return courseVo;
        }).collect(Collectors.toList());
//        返回结果集
        HashMap<String, Object> hashMapResult = new HashMap<>(2);
        hashMapResult.put("total", pageCourse.getTotal());
        hashMapResult.put("currentPage", pageCourse.getCurrent());
        hashMapResult.put("pageSize", pageCourse.getSize());
        hashMapResult.put("courseVoList", courseVoList);
        return hashMapResult;
    }

    @Override
    public Course getCourseById(Long id) {
        return this.getOne(new QueryWrapper<Course>().eq("course_id", id));
    }

    @Override
    public Boolean modifiedClassroom(Course course) {
        return this.updateById(course);
    }

    @Override
    public boolean deleteCourse(Long id) {
        return this.removeById(id);
    }

    @Override
    public Boolean saveCourse(Course course) {
        Boolean flag = this.checkData(course.getClassroomId(), course.getBeginTime(), course.getEndTime());
        if (!flag) {
            throw new CRException("时间有冲突，请更换教室或时间段");
        }
        return this.save(course);
    }

    @Override
    public Boolean checkData(Long id, LocalDateTime beginTime, LocalDateTime endTime) {
//        判断该时间段中班级是否空闲
        List<Course> courseList = this.courseMapper.selectCourseIsExists(id, beginTime, endTime);
        return CollectionUtil.isEmpty(courseList);
    }
}
